﻿namespace Xms.Abp.Components;

public class NNameValueDataSourceTypeSelect : Select<Guid?, NameValue<Guid?>>
{
    public NNameValueDataSourceTypeSelect()
    {
        LabelName = nameof(NameValue<Guid?>.Name);
        ValueName = nameof(NameValue<Guid?>.Value);
        EnableSearch = true;
    }
    [Inject] public IServiceProvider ServiceProvider { get; set; }

    [Parameter] public Type DataSourceType { get; set; }

    [Parameter] public string NullLabel { get; set; } = "请选择";

    protected override async Task OnInitializedAsync()
    {
        if (DataSource == null)
        {
            var nameValueService = DataSourceType != null ? ServiceProvider.GetService(DataSourceType) as INameValueService<Guid> : null;
            var list = await nameValueService?.GetNNameValuesAsync() ?? new List<NameValue<Guid?>>();
            if (!NullLabel.IsNullOrWhiteSpace())
            {
                list.Insert(0, new NameValue<Guid?>
                {
                    Name = NullLabel,
                    Value = null
                });
            }
            DataSource = list;
        }
        if (EnableSearch && !Disabled)
        {
            OnSearch = async filter => await OnSearchAsync(filter);
        }

        await base.OnInitializedAsync();
    }

    protected async Task OnSearchAsync(string filter)
    {
        var nameValueService = DataSourceType != null ? ServiceProvider.GetService(DataSourceType) as INameValueService<Guid> : null;
        var list = await nameValueService?.GetNNameValuesAsync(filter) ?? new List<NameValue<Guid?>>();
        if (!NullLabel.IsNullOrWhiteSpace())
        {
            list.Insert(0, new NameValue<Guid?>
            {
                Name = NullLabel,
                Value = null
            });
        }
        DataSource = list;
    }
}
